#include "stdafx.h"

#include "ResourcesManager.h"

namespace GMotor
{
	ResourcesManager::ResourcesManager(StdTools::LogManager * logManager)
	{
		this->thread = new StdTools::Threads::Thread(this);
		this->mLogManager = logManager;
	}

	ResourcesManager::~ResourcesManager()
	{
		StdTools::Threads::Thread::join(this->thread); //Esperamos a los procesos que todavia podrian estar ejecutandose

		std::list<ResourceGroup *>::iterator it;
		for (it = this->lstResourceGroup.begin(); it != this->lstResourceGroup.end(); it++)
			delete *it;
	}

	Resource * ResourcesManager::getResource(std::string name)
	{
		Resource * resource = NULL;
		bool encontrado = false;
		std::list<ResourceGroup *>::iterator it;
		for (it = this->lstResourceGroup.begin(); !encontrado && it != this->lstResourceGroup.end(); it++)
			if ((resource=(*it)->getResource(name))!=NULL)
				encontrado = true;
		return resource;
	}

	void ResourcesManager::addRegister(Register * newRegister)
	{
		this->lstRegister.push_back(newRegister);
	}

	void ResourcesManager::addResource(std::string path, std::string group)
	{
		Resource * resource = NULL;
		bool encontrador = false;
		std::list<Register *>::iterator rit;
		for (rit = this->lstRegister.begin(); !encontrador && rit != this->lstRegister.end(); rit++)
			if ((*rit)->canLoad(path))
			{
				encontrador = true;
				resource = (*rit)->create(path);

				bool encontradog = false;
				std::list<ResourceGroup *>::iterator git;
				for (git = this->lstResourceGroup.begin(); !encontradog && git != this->lstResourceGroup.end(); git++)
					if ((*git)->getName()==group)
					{
						encontradog = true;
						(*git)->addResource(resource);
					}
				if (!encontradog)
				{
					ResourceGroup * rg = new ResourceGroup(group,this->mLogManager);
					this->lstResourceGroup.push_back(rg);
					rg->addResource(resource);
				}
			}
	}

	void ResourcesManager::deleteResource(std::string name)
	{
		bool encontrado = false;
		std::list<ResourceGroup *>::iterator it;
		for (it = this->lstResourceGroup.begin(); !encontrado && it != this->lstResourceGroup.end(); it++)
			encontrado = (*it)->deleteResource(name);
	}

	void ResourcesManager::deleteGroup(std::string name)
	{
		bool encontrado = false;
		std::list<ResourceGroup *>::iterator it;
		for (it = this->lstResourceGroup.begin(); !encontrado && it != this->lstResourceGroup.end(); it++)
			if ((*it)->getName()==name)
				encontrado = true;
		if (encontrado)
		{
			it--;
			delete *it;
			this->lstResourceGroup.erase(it);
		}
	}

	void ResourcesManager::initializeAll()
	{
		this->thread->start();
	}

	void ResourcesManager::Run()
	{
		std::list<ResourceGroup *>::iterator it;
		for (it = this->lstResourceGroup.begin(); it != this->lstResourceGroup.end(); it++)
			(*it)->initialize();
	}
}